# Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt

import frappe
from frappe.utils import flt
from frappe import _


def execute(filters=None):
	data = []
	columns = get_columns()
	get_data(filters, data)
	return columns, data


def get_data(filters, data):
	get_exploded_items(filters.bom, data, limit_to_level = filters.limit_to_level)


def get_exploded_items(bom, data, indent=0, level='1', qty=1, limit_to_level = 0):
	if limit_to_level and (indent + 1) > int(limit_to_level):
		return
	item = frappe.qb.DocType('Item')
	bom_header = frappe.qb.DocType('BOM')
	bom_item = frappe.qb.DocType('BOM Item')

	exploded_items = frappe.qb.from_(bom_item
		).join(bom_header
		).on(bom_header.name == bom_item.parent
		).join(item
		).on(bom_header.item == item.name
		).select(bom_item.qty, bom_item.bom_no, bom_item.item_code.as_('comp_item_code'), 
			bom_item.item_name, bom_item.description, bom_item.uom,
			item.name.as_('parent_item_code'), item.item_name.as_('parent_item_name')
		).where(bom_header.name == bom
		).orderby(bom_item.idx
		).run(as_dict=1)		

	for (idx, item) in enumerate(exploded_items):
		item.level = f'{level}.{idx+1}'		
		item["indent"] = indent		 
		item.qty *= qty		
		data.append(item)
		if item.bom_no:
			get_exploded_items(item.bom_no, data, indent=indent + 1, level = item.level, qty=item.qty, limit_to_level=limit_to_level)


def get_columns():
	return [
		{"label": _("Level"), "fieldtype": "data", "fieldname": "level", "width": 120},
		{
			"label": _("Parent Item Code"),
			"fieldtype": "Link",
			"fieldname": "parent_item_code",
			"width": 120,
			"options": "Item",
		},
		{"label": _("Parent Item Name"), "fieldtype": "data", "fieldname": "parent_item_name", "width": 120},
		{
			"label": _("Item Code"),
			"fieldtype": "Link",
			"fieldname": "comp_item_code",	#用户item_code,系统会将item code 与 item_name自动合并
			"width": 120,
			"options": "Item",
		},
		{"label": _("Item Name"), "fieldtype": "data", "fieldname": "item_name", "width": 300},
		{"label": _("BOM"), "fieldtype": "Link", "fieldname": "bom_no", "width": 150, "options": "BOM"},
		{"label": _("Qty"), "fieldtype": "data", "fieldname": "qty", "width": 80},
		{"label": _("UOM"), "fieldtype": "data", "fieldname": "uom", "width": 70},
		#{"label": _("BOM Level"), "fieldtype": "Int", "fieldname": "bom_level", "width": 100},
		{
			"label": _("Item Description"),
			"fieldtype": "data",
			"fieldname": "description",
			"width": 350,
		},
	]


"""
testing
from zelin_pp.planning_enhancement.report.multi_level_bom.multi_level_bom import *
data = []
filters=frappe._dict({'bom':'BOM-多级BOM成品-001', 'limit_to_level':2})
get_data(filters, data)
"""